############################################################################            
#                               API                                        #
############################################################################



import string
import textwrap
import cgi
import logging
import json
import random
from datetime import datetime, date, time
from email.Generator import Generator
from db_model import Rooms, Members, Messages, RegularMessages, Polls, YouTube, FeedIndex
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import mail

logging.getLogger().setLevel(logging.INFO)



# Send a message to the server 
# Expect the following POST parameters :
#   RoomId  - the room to send the message to
#   UserId  - the user id 
#   Message - the message itself
# Return the message's Id
class SendMessage(webapp.RequestHandler):
  
  def post(self):
    roomId = self.request.get('RoomId')  
    userId = self.request.get('UserId') 
    
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return
 
    if not room.isUserMember(userId):
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members can send messages .
                              """)
      return
    
    message = RegularMessages()
    message.Room = room
    message.UserId = userId
    message.Message = self.request.get('Message')
    message.put()
    messageKey = message.key()
     
    self.response.out.write('%s' % messageKey)
    FeedIndex.Add(message)
    return


  
# Send a YouTube message to the server 
# Expect the following POST parameters :
#   RoomId   - the room to send the message to
#   UserId   - the user id 
#   Headline - the YouTube headline
#   Link     - the YouTube link
# Return the YouTube message's Id
class SendYouTube(webapp.RequestHandler):
  
  def post(self):
    roomId = self.request.get('RoomId')  
    userId = self.request.get('UserId') 
    
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return
 
    if not room.isUserMember(userId):
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members can send messages .
                              """)
      return
    
    message = YouTube()
    message.Room = room
    message.UserId = userId
    message.Headline = self.request.get('Headline')
    message.Link = self.request.get('Link')
    message.put()
    messageKey = message.key()
    
    FeedIndex.Add(message)
     
    self.response.out.write('%s' % messageKey)
    return

  
  
# Remove a message 
# Expect the following POST parameters :
#   RoomId    - the room's Id
#   UserId    - the user Id
#   MessageId - the message Id
# Return 1 for success  
class RemoveMessage(webapp.RequestHandler):
  
  def post(self):  
    userId    = self.request.get('UserId')
    messageId = self.request.get('MessageId') 
    
    message = Messages.get(messageId)
    if not message.UserId == userId :
      room = message.Room
      if not room.OwnerId == userId :
        self.response.out.write("""You are not the message publisher or the room owner !<br>
                                Only them can remove a message .    
                                """)
        return
    
    FeedIndex.Remove(message)  
    message.delete()    
    
    self.response.out.write('1')       
    return
  
  
    
# Create a new room, and make the user who created it as the owner
# Expect the following POST parameters :
#   RoomName - the room's name
#   UserId   - the user id
#   UserName - the user name
# Return the room's Id    
class CreateRoom(webapp.RequestHandler): 
  
  def createRoom(cls, roomName, userId, userName):
    room = Rooms()
    room.Name = roomName
    room.OwnerId = userId
    room.put()
    roomKey = room.key()
    
    members = Members()
    members.Room = room
    members.MemberId = userId
    members.Nick = userName
    members.put()
    
    message = RegularMessages()
    message.Room = room
    message.UserId = userId
    message.Message = 'Hi! Welcome to the "%s" room. You can use the invite (above) to add your friends to the room.' % roomName  
    message.put()
    FeedIndex.Add(message)
    
    return roomKey
    
  createRoom = classmethod(createRoom)  
     
  def post(self):  
    roomName = self.request.get('RoomName')
    userId   = self.request.get('UserId')
    userName = self.request.get('UserName')
    
    roomKey = self.createRoom(roomName, userId, userName)    
          
    self.response.out.write('%s' % roomKey)
    return



# Remove a room 
# Expect the following POST parameters :
#   RoomId - the room's Id
#   UserId - the user id
# Return 1 for success    
class RemoveRoom(webapp.RequestHandler):  
  
  def post(self):  
    roomId = self.request.get('RoomId')
    userId = self.request.get('UserId')
   
    try :
      room = Rooms.get(roomId)    
    except :
      self.response.out.write("Invalid room Id !")
      return

    roomOwner = room.OwnerId  
    if not roomOwner == userId :
      self.response.out.write("""
                              You are not the room owner !<br>
                              Only the room owner can remove this room .
                              """)
      return 
    
    #remove from Members
    query = Members.Query()
    members = query.filter('Room', room)
    for member in members :
      member.delete()
    #remove from Messages
    query = Messages.Query()
    messages = query.filter('Room', room) 
    for message in messages :
      FeedIndex.Remove(message)
      message.delete()
    #remove from Rooms
    room.delete()  
      
    self.response.out.write('1')  
    return
    
           
                
# Add a member to a room
# Expect the following POST parameters :
#   UserId      - the user id
#   RoomId      - the room's Id
#   MemberId    - the new member's Id   
#   MemberName  - the new member's nickname
#   MemberEmail - the new member's email
# Return 1 for success
class AddMember(webapp.RequestHandler):  
  
  def post(self):  
    userId      = self.request.get('UserId')
    userEmail   = "tau.mim.gadget@gmail.com"
    roomId      = self.request.get('RoomId')
    memberId    = self.request.get('MemberId')
    nick        = self.request.get('MemberName')
    memberEmail = self.request.get('MemberEmail')
    
    try :
      room = Rooms.get(roomId)    
    except :
      self.response.out.write("Invalid room Id !")
      return
    
    if not room.isUserMember(userId):
      self.response.out.write("""
                              You are not a room member !<br>
                              Only room members can add new members to the room .  
                              """) 
      return
    
    if room.isUserMember(memberId):
      self.response.out.write("%s is already a member in this room !"  % memberId)
      return
    
    members = Members()
    members.MemberId = memberId
    members.Room = room
    members.Nick = nick
    members.put()
    
    message = RegularMessages()
    message.Room = room
    message.UserId = userId
    message.Message = 'User %s has been invited to the room' % nick
    message.put()
    FeedIndex.Add(message)
      
    #send email to the new member
    roomName = room.Name
    str = nick, roomName   
    try :
      if ((mail.is_email_valid(userEmail)) & (mail.is_email_valid(memberEmail))) :
        subject = "You are invited to TAU-MIM room %s" % roomName
        body = """
                                 Dear %s ,
                                 
                                 You are now a member in the "%s" tau-mim room.
                                 You are invite to visit the room.
                                 
                                 If you don't have the Gadget running, you can start using it by clicking http://www.google.com/ig/adde?source=atgs&moduleurl=tau-mim.googlecode.com/svn/trunk/gadget/MIM.xml
                                 
                                 TAU-MIM Team    
                                 """ % str
                                 
        message = mail.EmailMessage()
        message.sender = userEmail
        message.to = memberEmail
        message.subject=subject
        message.body = body
        
        message.send()
            
#        mail.send_mail(sender  = userEmail                         ,
#                       to      = memberEmail                       ,
#                       subject = subject ,
#                       body    = body)
                       
        logging.log(logging.INFO, "Sending email successfully to %s" % memberEmail)
    except Exception :
      errMessage = []
      errMessage.append("Sending email failed!")
      errMessage.append(" exp %s " % Exception.message)
      errMessage.append(" sender %s " % userEmail)
      errMessage.append(" recipient %s " % memberEmail)
      errMessage.append(" subject %s " % memberEmail)
      errMessage.append(" body %s " % body)      
      logging.log(logging.ERROR, ''.join(errMessage)); 
      
    self.response.out.write('1')
    return


 
# Remove a member from a room
# Expect the following POST parameters :
#   UserId   - the user id
#   RoomId   - the room's Id
#   MemberId - the member's Id
# Return 1 for success   
class RemoveMember(webapp.RequestHandler):  
  
  def post(self):  
    userId = self.request.get('UserId')
    roomId = self.request.get('RoomId')
    
    try :
      room = Rooms.get(roomId)    
    except :
      self.response.out.write("Invalid room Id !")
      return
    
    if not room.OwnerId == userId :
      self.response.out.write("""
                              You are not the room owner !<br>
                              Only the room owner can remove a member from the room .
                              """)
      return 
     
    memberId = self.request.get('MemberId')
    if userId == memberId :
      self.response.out.write("""
                              You are the room owner .<br>
                              If you want to remove yourself you must remove the entire room using RemoveRoom .
                              """)                               
      return 
    
    query = Members.Query()
    query.filter('Room', room)
    query.filter('MemberId', memberId)
    member = query.get()
    member.delete()
    
    self.response.out.write('1')
    return
     
 
 
# Change user Nickname in a room
# Expect the following POST parameters :
#   UserId  - the user id
#   RoomId  - the room Id
#   NewNick - the new nickname
# Return 1 for success
class ChangeNick(webapp.RequestHandler):
  
  def post(self):
    userId  = self.request.get('UserId') 
    roomId = self.request.get('RoomId')
    
    try :
      room = Rooms.get(roomId)    
    except :
      self.response.out.write("Invalid room Id !")
      return
    
    if not room.isUserMember(userId):
       self.response.out.write("You are not a member in this room !")
       return 
        
    newNick = self.request.get('NewNick')
    query = Members.Query()
    query.filter('Room', room)
    query.filter('MemberId', userId)
    member = query.get()
    member.Nick = newNick
    member.put()
    
    self.response.out.write('1')
    return
  
  
  
# Create a JSON of the room's messages 
# Expect the following GET parameters : 
#   RoomId   - the required room
#   UserId   - the user's id
#   Messages - number of messages to retrieve (If missing, then 10 will be brought) .
#   Offset   - the index of the first message to retrieve (0 by default)
class GetRoomMessages(webapp.RequestHandler):
   
  def get(self):
    roomId = self.request.get('RoomId')
    userId = self.request.get('UserId')
    
    try :
      maxMessages = int(self.request.get('Messages'))
    except :
      maxMessages = 10      
    if maxMessages < 1 : maxMessages = 10
    
    try :
      offset = int(self.request.get('Offset'))
    except :
      offset = 0      
    if offset < 0 : offset = 0
      
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return

    if (room is None):
      self.response.out.write("Invalid room Id !")
      return
      
    if (not room)|(not room.isUserMember(userId)):
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members are allowed to view the room's messages list .
                              """)
      return
    
    owner  = (room.OwnerId==userId)
    header = {'roomId'   : "%s" % roomId   , 
              'roomName' : "%s" % room.Name,
              'owner'    : owner
             }
        
    query = Messages.Query()
    query.filter('Room', room)
    query.order('-TimeStamp')
    messages = query.fetch(limit = maxMessages, offset = offset)
      
    jsonMessages = []
    
    for message in messages : 
      nick = Members.GetNick(message.UserId, room)

      messageType = message.messageType()
      jsonMessage = {'id'        : "%s" % message.key()    ,
                     'timestamp' : "%s" % message.TimeStamp, 
                     'username'  : "%s" % message.UserId   ,
                     'nickname'  : "%s" % nick             ,                    
                    }
      
      if messageType == "RegularMessages" :
        jsonMessage['type']    = "regular"
        jsonMessage['comment'] = "%s" % message.Message
        
      if messageType == "YouTube" :
        jsonMessage['type']     = "youTube"
        jsonMessage['Headline'] = "%s" % message.Headline
        jsonMessage['Link']     = "%s" % message.Link
             
      if messageType == "Polls" :
        if message.isUserParticipated(userId):
          type = "pollResult"
        else:
          type = "pollQuestion"  
        jsonMessage['type']     = type
        jsonMessage['question'] = "%s" % message.Question
        answers = [];
        
        for i in range(len(message.Answers)):
          if message.isUserParticipated(userId):
            answers.append({'answer' : '%s' % message.Answers[i],
                            'count'  : '%s' % message.Votes[i]})
          else:
            answers.append('%s' % message.Answers[i])
        
        jsonMessage['answers'] = answers
        
      if messageType == "YouTube" :
        jsonMessage['type'] = "youTube"
        jsonMessage['link'] = "%s" % message.Link  
                
      jsonMessages.append(jsonMessage)      
      
    result = [ header, jsonMessages ]
    
    self.response.out.write(json.write(result))
    return             



# Create a JSON of the room's members 
# Expect the following GET parameters : 
#   UserId - the user's id
#   RoomId - the required room
class GetRoomMembers(webapp.RequestHandler):
  
  def get(self):
    userId = self.request.get('UserId')
    roomId = self.request.get('RoomId')
    
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return
    
    if not room.isUserMember(userId):
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members are allowed to view the room's members list .
                              """)
      return
    
    header = {'roomId'   : "%s" % roomId   , 
              'roomName' : "%s" % room.Name
             }
    
    query = Members.Query()
    members = query.filter('Room', room)
    
    jsonMessages = []
    for member in members :
      jsonMessage= {'memberid' : "%s" % member.MemberId,
                    'nickname' : "%s" % member.Nick    ,
                   }
      jsonMessages.append(jsonMessage)
      
    result = [ header, jsonMessages ]
    
    self.response.out.write(json.write(result))
    return    



# Create a JSON of the user's rooms
# Expect the following GET parameters :
#   UserId   - the user's id
#   UserName - the user's name
class GetUserRooms(webapp.RequestHandler):
  
  def get(self):
    userId = self.request.get('UserId') 
    userName = self.request.get('UserName')
    
    members = Members.Query()
    members.filter('MemberId', userId)
    num = members.count()
    if num < 1 :
      CreateRoom.createRoom(userName, userId, userName)
      
    jsonRooms = []
    for roomMember in members :
      myRoom = roomMember.Room
      roomId = myRoom.key()
      roomName = myRoom.Name
      owner = (myRoom.OwnerId==userId)
      jsonRoom = {'roomId'   : '%s' % roomId  ,
                  'roomName' : '%s' % roomName, 
                  'owner'    :  owner 
                 }
      jsonRooms.append(jsonRoom)
      
    self.response.out.write(json.write(jsonRooms))
    return
  
  

# Create a JSON of the room statistics
# Expect the following GET parameters :
#   UserId           - the user's id
#   RoomId           - the room's id
#   Year, Month, Day - regard messages start from (If missing then regard all) .    
class GetRoomStatistics(webapp.RequestHandler): 
  
  def get(self):
    userId = self.request.get('UserId')
    roomId = self.request.get('RoomId')
    
    try :
      year = int(self.request.get('Year'))
    except :
      year = 2000
    try :
      month = int(self.request.get('Month'))
    except :
      month = 1
    try :
      day = int(self.request.get('Day'))
    except :
      day = 1   
    date = datetime(year, month, day)
    
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return
     
    if not room.isUserMember(userId) :
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members are allowed to view the room's statistics .
                              """)
      return

    header = {'roomId'   : "%s" % roomId   , 
              'roomName' : "%s" % room.Name
             }
    
    query = Members.Query()
    members = query.filter('Room', room)
    jsonMembersMessages = []
    for member in members :
      query = Messages.Query()
      query.filter('TimeStamp >=', date)
      query.filter('Room', room)
      query.filter('UserId', member.MemberId)
      num = query.count()
      jsonMember = {'memberid'       : "%s" % member.MemberId,
                    'nickname'       : "%s" % member.Nick    ,
                    'numofmessages'  : "%d" % num            ,
                   }
      jsonMembersMessages.append(jsonMember)
      
    result = [ header, jsonMembersMessages ]
    
    self.response.out.write(json.write(result))
    return
  
  
  
# Create a JSON of with number of times a certain text is in the room's 
# regular messages and the messages it's in
# Expect the following GET parameters :
#   UserId   - the user's id
#   RoomId   - the room's id
#   MyText   - the wanted text  
#   Messages - number of messages to search in       
class GetWordCount(webapp.RequestHandler):
   
  def findSubstring(text, substring):
    pos = - 1
    list = []
    while True :
      # move index up on next call
      pos = text.find(substring, pos + 1)
      # not found or done
      if pos < 0 :
        break
      list.append(pos)
     
    return list
     
  findSubstring = staticmethod(findSubstring)

  def get(self) :
    userId = self.request.get('UserId')
    roomId = self.request.get('RoomId')
    myText = self.request.get('MyText')
   
    try :
      maxMessages = int(self.request.get('Messages'))
    except :
      maxMessages = 10     
    if maxMessages < 1 : maxMessages = 10 
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return
 
    if not room.isUserMember(userId) :
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members are allowed to view the room's messages list .
                              """)
      return

    header = {'roomId'   : "%s" % roomId   ,
              'roomName' : "%s" % room.Name
             }
       
    query = RegularMessages.Query()
    query.filter('Room', room)
    query.order('-TimeStamp')
    messages = query.fetch(limit = maxMessages)
     
    jsonMessages = []
    indexes = []
    wordCount = 0
    for message in messages :
      query = Members.Query()
      query.filter('Room', room)
      query.filter('MemberId', message.UserId)
      member = query.get()
      nick = member.Nick
      myStr = str (message.Message)
      index = myStr.find(myText)
      indexes = GetWordCount.findSubstring(myStr, myText)
      wordCount += len(indexes)
      if len(indexes) > 0 :   
        jsonMessage= {'comment'   : "%s" % myStr            ,
                      'username'  : "%s" % message.UserId   ,
                      'nickname'  : "%s" % nick             ,
                      'timestamp' : "%s" % message.TimeStamp,
                      'indexes'   : "%s" % str(indexes)     ,
                     }
        jsonMessages.append(jsonMessage)
        
    jsonMessages.append(wordCount)
    result = [ header, jsonMessages ]
    
    self.response.out.write(json.write(result))
    return                 


  
# Send a poll to the server to publish 
# Expect the following POST parameters :
#   RoomId   - the room to publish the poll to
#   UserId   - the user Id of the poll publisher
#   Question - the poll question
#   Answers  - optional answers to the poll (in Json format)
# Return the poll's Id
class CreatePoll(webapp.RequestHandler):
  
  def post(self):
    roomId      = self.request.get('RoomId')  
    userId      = self.request.get('UserId')
    question    = self.request.get('Question')
    answersJSON = self.request.get('Answers')
     
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return
 
    if not room.isUserMember(userId):
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members can publish polls .
                              """)
      return   

    poll = Polls()
    poll.Room = room
    poll.UserId = userId
    poll.Question = question 
    poll.Answers = json.read(answersJSON)
    numOfAnswers = len(poll.Answers)
    poll.Votes = []
    for i in range(numOfAnswers):
      (poll.Votes).append(0)  
    poll.Participaters = []
    poll.put()
    FeedIndex.Add(poll)
    pollKey = poll.key()
        
    self.response.out.write('%s' % pollKey)
    return 



# Send a filled poll to the server 
# Expect the following POST parameters :
#   RoomId       - the room the poll is published in
#   UserId       - the user id 
#   AnswerNumber - the number of the answer the user choose  
#       pre cond: AnswerNumber <= number of possible answers
# Return 1 for success
class AnswerPoll(webapp.RequestHandler):
  
  def post(self):
    roomId       = self.request.get('RoomId')  
    userId       = self.request.get('UserId')
    pollId       = self.request.get('MessageId')
    answerNumber = int(self.request.get('Answer')) 
    
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return
 
    if not room.isUserMember(userId) :
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members can participate in the room polls .
                              """)
      return
    
    try :
      poll = Polls.get(pollId)
    except :
      self.response.out.write("Invalid poll Id !")
      return
    
    if  poll.isUserParticipated(userId):
      self.response.out.write("You have already participated in this poll !")
      return
    
    (poll.Participaters).append(userId)
    poll.Votes[answerNumber - 1] = poll.Votes[answerNumber - 1] + 1
    poll.put()
    
    self.response.out.write('1')
    return
  
  
  
# Create a JSON of the room's polls 
# Expect the following GET parameters : 
#   RoomId   - the required room
#   UserId   - the user's id
#   Polls    - number of polls to retrieve (If missing, then 10 will be brought)
class GetRoomPolls(webapp.RequestHandler):
   
  def get(self):
    roomId = self.request.get('RoomId')
    userId = self.request.get('UserId')
    
    try :
      maxPolls = int(self.request.get('Polls'))
    except :
      maxPolls = 10      
    if maxPolls < 1 : maxPolls = 10
      
    try :
      room = Rooms.get(roomId)
    except :
      self.response.out.write("Invalid room Id !")
      return
  
    if not room.isUserMember(userId):
      self.response.out.write("""
                              You are not a member in this room !<br>
                              Only room members are allowed to view the room's polls list .
                              """)
      return

    header = {'roomId'   : "%s" % roomId   , 
              'roomName' : "%s" % room.Name
             }
        
    query = Polls.Query()
    query.filter('Room', room)
    query.order('-TimeStamp')
    polls = query.fetch(limit = maxPolls)
      
    jsonPolls = []
    for poll in polls :
      numOfAnswers = len(poll.Answers)
      
      
      jsonPoll = {}
      if poll.isUserParticipated(userId):
          type = "pollResult"
      else :
          type = "pollQuestion"
        
      jsonPoll['type']      = type
      jsonPoll['question']  = "%s" % poll.Question
      jsonPoll['timestamp'] = "%s" % poll.TimeStamp
      jsonPoll['pollId']    = "%s" % poll.key() 
      jsonPoll['userId']    = "%s" % poll.UserId

      answers = []
        
      for i in range(numOfAnswers):
        if poll.isUserParticipated(userId):
          answers.append({'answer' : '%s' % poll.Answers[i],
                          'count'  : '%s' % poll.Votes[i]})
        else:
          answers.append('%s' % poll.Answers[i])
      
      jsonPoll['answers'] = answers
                   
      jsonPolls.append(jsonPoll)
      
    result = [ header, jsonPolls ]
    
    self.response.out.write(json.write(result))
    return  
  
  
  
# Create a JSON of the last messages from the rooms the user is member in 
# Expect the following GET parameters : 
#   UserId   - the user's id
#   Messages - number of messages to retrieve
#   Offset   - starting from what message index
class GetUserFeed(webapp.RequestHandler):
  
  def get(self):
    userId = self.request.get('UserId')
    userName=self.request.get('UserName')
    
    try :
      maxMessages = int(self.request.get('Messages'))
    except :
      maxMessages = 10      
    if maxMessages < 1 : maxMessages = 10  
    
    try :
      offset = int(self.request.get('Offset'))
    except :
      offset = 0      
    if offset < 0 : offset = 0
    
    
    query=FeedIndex.Query()
    query.filter("MemberId", userId)
    query.order("-TimeStamp")
    
    feedList = query.fetch(limit = maxMessages, offset = offset)
    
    if (query.count()==0):
      CreateRoom.createRoom(userName, userId, userName)
      query=FeedIndex.Query()
      query.filter("MemberId", userId)
      query.order("-TimeStamp")
      feedList = query.fetch(limit = maxMessages, offset = offset)  

    jsonFeeds = []
    
    for feedEntity in feedList:
      message = feedEntity.Message  
      jsonMessage = {}
      userId = message.UserId
      roomId = message.Room.key()

      nick = Members.GetNick(userId, roomId)
      
      jsonMessage['roomId']    = "%s" % roomId
      jsonMessage['roomName']  = "%s" % message.Room.Name
      jsonMessage['id']        = "%s" % message.key()
      jsonMessage['timestamp'] = "%s" % message.TimeStamp 
      jsonMessage['username']  = "%s" % userId
      jsonMessage['nickname']  = "%s" % nick

      messageType = message.messageType()
      jsonMessage['class'] = "%s" % messageType
      if (messageType == "RegularMessages") | (messageType == "Messages"):
        jsonMessage['type']    = "regular"
        jsonMessage['comment'] = "%s" % message.Message
         
      if messageType == "Polls" :
        if message.isUserParticipated(userId):
          type = "pollResult"
        else :
          type = "pollQuestion"

        jsonMessage['type']     = type
        jsonMessage['question'] = "%s" % message.Question
        answers = [];
        
        for i in range(len(message.Answers)):
          if message.isUserParticipated(userId):
            answers.append({'answer' : '%s' % message.Answers[i],
                            'count'  : '%s' % message.Votes[i]})
          else :
            answers.append('%s' % message.Answers[i])

        jsonMessage['answers'] = answers

      if messageType == "YouTube" :
        jsonMessage['type']     = "youTube"
        jsonMessage['Headline'] = "%s" % message.Headline
        jsonMessage['Link']     = "%s" % message.Link
        
      
      jsonFeeds.append(jsonMessage)
      
    self.response.out.write(json.write(jsonFeeds)) 
    return  
  
  

# Find out how many messages in the room are newer then the given time stamp 
# Expect the following GET parameters : 
#   RoomId - the required room
#   Time   - the given time stamp 
# Return the number of newer messages (0 for none) 
class NumOfNewMessages(webapp.RequestHandler):
      
  def get(self):
    self.response.headers.add_header("Expires", "-1")
    self.response.headers.add_header("Pragma", "no-cache")
    
    roomId = self.request.get('RoomId')   
    time   = (self.request.get('Time'))
    if time == "" :
      time = "2000-01-01 10:00:00.000001"

    dateTime = time.split(' ')
    date = dateTime[0].split('-')
    ttime = dateTime[1].split('.')
    time = ttime[0].split(":")
    ms = int(ttime[1]);
    hour = int(time[0])
    min = int(time[1])
    sec = int(time[2])
    year = int(date[0])
    month = int(date[1])
    day = int(date[2])
    dt = datetime(year, month, day, hour, min, sec, ms)
    
    try :
      room = Rooms.get(roomId)
      query = Messages.Query()
      query.filter('Room', room)
      query.filter('TimeStamp >', dt)
      num = query.count()
    except :
      num = 1
      
    self.response.out.write("%d"  % num) 
    return
